#!/usr/bin/python
# -*- coding: UTF-8 -*-

import smtplib
from email.header import Header
from email.mime.application import MIMEApplication
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr

from ZIndex.tool import imageUtil


def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))


def get_server(username):
    """
    通过邮箱地址获得邮箱服务器
    :param username:用户名，比如：123456@qq.com
    :return: 邮箱服务器地址，可以根据自己实际业务添加，比如：smtp.qq.com
    """
    servers = {'qq': 'smtp.qq.com'
        , '126': 'smtp.126.com'
        , '163': 'smtp.163.com'
        , '139': 'smtp.139.com'}

    for key, value in servers.items():
        if key in username:
            return value


def send_mail(username, password, to, sender_name, subject, content, email_type):
    """
    :param username:
    :param password:
    :param to: 接收者列表 []
    :param sender_name:
    :param subject:
    :param content:
    :param email_type:
    :return:
    """
    from_addr = username
    password = password
    to_addr = to
    smtp_server = get_server(username)

    # 邮件正文是MIMEText类型
    msg = MIMEText('%s' % (content), '%s' % (email_type), 'utf-8')
    msg['From'] = _format_addr('%s<%s>' % (sender_name, from_addr))
    msg['To'] = _format_addr('<%s>' % to_addr)
    msg['Subject'] = Header('%s' % (subject), 'utf-8').encode()

    # 普通登陆端口是25，带ssl验证时候端口是465
    # smtp_server = 'smtp.exmail.qq.com'
    # server = smtplib.SMTP_SSL(smtp_server, 465)
    server = smtplib.SMTP(smtp_server, 25)
    server.set_debuglevel(1)
    server.login(from_addr, password)
    server.sendmail(from_addr, to_addr, msg.as_string())
    server.quit()




def send_mail_multipart(username, password, to, sender_name, subject, content, email_type, filename):
    from_addr = username
    password = password
    to_addr = to
    smtp_server = get_server(username)

    msg = MIMEMultipart()
    # 邮件正文是MIMEText类型
    msg.attach(MIMEText('%s' % (content), '%s' % (email_type), 'utf-8'))
    msg['From'] = _format_addr('%s<%s>' % (sender_name, from_addr))
    msg['To'] = _format_addr('<%s>' % to_addr)
    msg['Subject'] = Header('%s' % (subject), 'utf-8').encode()


    # 添加附件
    mime = MIMEApplication(open(filename, 'rb').read())
    mime.add_header('Content-Disposition', 'attachment', filename='important.csv')
    # 添加到MIMEMultipart:
    msg.attach(mime)

    # 普通登陆端口是25，带ssl验证时候端口是465
    # smtplib.SMTP_SSL(smtp_server, 465)
    server = smtplib.SMTP(smtp_server, 25)
    server.set_debuglevel(1)
    server.login(from_addr, password)
    server.sendmail(from_addr, [to_addr], msg.as_string())
    server.quit()

def send_mail_content_multipart(username, password, to, sender_name, subject, content, email_type, filename, lbFig=None, tradeFig=None):
    from_addr = username
    password = password
    to_addr = to
    smtp_server = get_server(username)

    msg = MIMEMultipart('related')

    msg['From'] = _format_addr('%s<%s>' % (sender_name, from_addr))
    msg['To'] = _format_addr('<%s>' % to_addr)
    msg['Subject'] = Header('%s' % (subject), 'utf-8').encode()

    # 添加附件
    mime = MIMEApplication(open(filename, 'rb').read())
    mime.add_header('Content-Disposition', 'attachment', filename='important.csv')
    # 添加到MIMEMultipart:
    msg.attach(mime)

    # codename-2, LB=12

    # 添加图片
    lb = open(lbFig, 'rb')
    image_infolb = MIMEImage(lb.read())
    lb.close()
    image_infolb.add_header('Content-Id', '<image1>')
    msg.attach(image_infolb)
    # codename-2, trade=12

    # 添加图片
    trade = open(tradeFig, 'rb')
    image_infotrade = MIMEImage(trade.read())
    trade.close()
    image_infotrade.add_header('Content-Id', '<image2>')
    msg.attach(image_infotrade)

    lb_pic_inline = f'''
                        <br><img src="cid:image1" width="300" ></br>
                        '''
    trade_pic_inline = f'''
                            <br><img src="cid:image2" width="300" ></br>
                            '''
    # 邮件正文是MIMEText类型
    msg.attach(MIMEText('%s' % (content + lb_pic_inline + trade_pic_inline), '%s' % (email_type), 'utf-8'))

    # 普通登陆端口是25，带ssl验证时候端口是465
    # smtplib.SMTP_SSL(smtp_server, 465)
    server = smtplib.SMTP(smtp_server, 25)
    server.set_debuglevel(1)
    server.login(from_addr, password)
    server.sendmail(from_addr, [to_addr], msg.as_string())
    server.quit()

#
def send_mail_content_multipart2(username, password, to, sender_name, subject, content, email_type, filename, figList=None):
    """
    :param username:
    :param password:
    :param to:
    :param sender_name:
    :param subject:
    :param content:
    :param email_type:
    :param filename: 附件名称
    :param figList: 图片列表list
    :return: 发送图片列表带附件和内容的邮件
    """
    from_addr = username
    password = password
    to_addr = to
    smtp_server = get_server(username)

    msg = MIMEMultipart('related')

    msg['From'] = _format_addr('%s<%s>' % (sender_name, from_addr))
    msg['To'] = _format_addr('<%s>' % to_addr)
    msg['Subject'] = Header('%s' % (subject), 'utf-8').encode()

    # 添加附件
    mime = MIMEApplication(open(filename, 'rb').read())
    mime.add_header('Content-Disposition', 'attachment', filename='important.csv')
    # 添加到MIMEMultipart:
    msg.attach(mime)
    pic_content = ''
    # 添加图片
    if figList != None and len(figList) > 0 :
        # 循环图片列表
        for i, val in enumerate(figList):
            fig = open(val, 'rb')
            image_info = MIMEImage(fig.read())
            fig.close()
            figNum = str(i)+'A'
            print(val)
            image_info.add_header('Content-Id', '<image'+figNum+'>')
            msg.attach(image_info)
            pic_content = pic_content + f'''
                        <br><img src="cid:image'''+figNum +'''" width="300" ></br>
                        '''
    print("######pic_content####")
    print(pic_content)

    # 邮件正文是MIMEText类型
    msg.attach(MIMEText('%s' % (content + pic_content), '%s' % (email_type), 'utf-8'))

    # 普通登陆端口是25，带ssl验证时候端口是465
    # smtplib.SMTP_SSL(smtp_server, 465)
    server = smtplib.SMTP(smtp_server, 25)
    server.set_debuglevel(1)
    server.login(from_addr, password)
    server.sendmail(from_addr, [to_addr], msg.as_string())
    server.quit()



def sendStockEmail(type, receiveList,  filename=None):
    """
       :param type: 邮件发送类型，有简单邮件type=1, 附件邮件type=2,filename不为空
       :param imp_stock_list: 重点关注股票，
       :param receiveList： 接收者列表 如receiveList = ['494037935@qq.com', 'znufe2018@qq.com']
       :return:
       使用163邮箱发送邮件，
       """

    username = 'znufe2020@163.com'
    password = 'MDOHKQGTQPUPRTTY'
    sender_name = 'znufe2020@163.com'
    subject = '每日关注'
    content = '<html><h1>祝各位老板发大财</h1></html>'
    # email_type 取值：plain,文本类型邮件;html,html类型邮件
    email_type = 'html'
    # _to = ['494037935@qq.com', 'znufe2018@qq.com']

    ### 生成图片 begin
    lbFig = imageUtil.genImage(filename, 2, 12)
    tradeFig = imageUtil.genImage(filename, 2, 13)

    ### 生成图片 end

    for to in receiveList:
        if type == 1:
            # 发送简单文本邮件
            send_mail(username, password, to, sender_name, subject, content, email_type)
        elif type == 2 and filename != None:
            # 发送带附件邮件
            send_mail_multipart(username, password, to, sender_name, subject, content, email_type, filename)
        elif type == 3 and filename != None:
            # 发送图片内容带附件邮件
            send_mail_content_multipart(username, password, to, sender_name, subject, content, email_type, filename, lbFig, tradeFig)
        print('send mail to %s success' % to)


def sendStockListEmail(type, receiveList, filename, figList=None):
    """
       :param type: 邮件发送类型，有简单邮件type=1, 附件邮件type=2,filename不为空
       :param imp_stock_list: 重点关注股票，
       :param receiveList： 接收者列表 如receiveList = ['494037935@qq.com', 'znufe2018@qq.com']
       :param figList：图片名称列表 ['../ZIndex/result/code_name--LB.png', '../ZIndex/result/code_name--换手率.png']
       :return:
       使用163邮箱发送邮件，
       """

    username = 'znufe2020@163.com'
    password = 'MDOHKQGTQPUPRTTY'
    sender_name = 'znufe2020@163.com'
    subject = '每日关注'
    content = '<html><h1>祝各位老板发大财</h1></html>'
    # email_type 取值：plain,文本类型邮件;html,html类型邮件
    email_type = 'html'
    # _to = ['494037935@qq.com', 'znufe2018@qq.com']

    for to in receiveList:
        if type == 1:
            # 发送简单文本邮件
            send_mail(username, password, to, sender_name, subject, content, email_type)
        elif type == 2 and filename != None:
            # 发送带附件邮件
            send_mail_multipart(username, password, to, sender_name, subject, content, email_type, filename)
        elif type == 3 and figList != None and len(figList) > 0 :
            # 发送图片内容带附件邮件
            send_mail_content_multipart2(username, password, to, sender_name, subject, content, email_type, filename, figList)
        print('send mail to %s success' % to)




 # MDOHKQGTQPUPRTTY
if __name__ == '__main__':
    """发送简单文本邮件"""
    username = 'znufe2020@163.com'
    password = 'MDOHKQGTQPUPRTTY'
    sender_name = 'znufe2020@163.com'
    subject = '每日关注'
    content = '<html><h1>祝各位老板发大财</h1></html>'
    # email_type 取值：plain,文本类型邮件;html,html类型邮件
    email_type = 'html'
    _to = ['494037935@qq.com', 'yzhch2007@163.com', '395065182@qq.com', '407031214@qq.com']



    filename = '../result/ZIndexSignDay.csv'
    ### 生成图片 begin
    lbFig = imageUtil.genImage(filename, 2, 12)
    tradeFig = imageUtil.genImage(filename, 2, 13)
    ### 生成图片 end

    for to in _to:
        # send_mail(username, password, to, sender_name, subject, content, email_type)
        # send_mail_multipart(username, password, to, sender_name, subject, content, email_type, filename)
        send_mail_content_multipart(username, password, to, sender_name, subject, content, email_type, filename, tradeFig)

        print('send mail to %s success' % to)
    # xlabels = 2
    # ylabels = 12
    # genImage(filename, xlabels, ylabels)